'''
# Coding:utf-8
# Project: online-exam
# Author: rtf
# Time: 2022-07-29 17:08:11
# FileName: upload.py
# Software: PyCharm
'''

from sanic.response import json
import os
import datetime
from trump.utils import ok


UPLOAD_PATH = os.path.join(f"{os.getcwd()}/upload/")


async def save_file(request, file):
    params = request.form
    t = datetime.datetime.now()
    filepath = os.path.join(UPLOAD_PATH, t.strftime('%Y%m%d'))
    if not os.path.isdir(filepath):
        os.mkdir(filepath)
    suffix = file.name.split(".")
    suffix = suffix[len(suffix) - 1]
    if params and params.get("filename"):
        file_name = f'{params.get("filename")}.{suffix}'
        filename = os.path.join(filepath, params.get("filename"))
    else:
        file_name = file.name
        filename = os.path.join(filepath, file_name)

    with open(filename + 'tmp', 'wb+') as f:
        f.write(file.body)
    os.rename(filename + 'tmp', f"{filename}")
    url = os.path.join(t.strftime('%Y%m%d'), f"{file_name}")
    return f"/download/{url}"


async def post(app, request):
    filetype = request.files.get('file')
    # 判断文件分类
    if not filetype:
        return json({"": 1, "data": "\"type\" field is not found."})
    r = await save_file(request, request.files.get('file'))
    return ok(r)